import React, { useState, useEffect, useRef } from "react";
import { Link } from "react-router-dom";
import HomeHead from "@/components/HomeHead.jsx";
import NewsItem from "@/components/NewsItem.jsx";
import MySkeleton from "@/components/MySkeleton.jsx";
import { Swiper, Image, Divider, DotLoading } from "antd-mobile";
import { formatTime } from "@/utils/utils";
import Api from "@/api";
import "./Home.scss";

export default function Home() {
  const [today, setToday] = useState(formatTime(new Date(), "{0}{1}{2}")),
    [bannerData, setBannerDate] = useState([]),
    [newList, setNewList] = useState([]);

  let loadmore = useRef();

  // 组件渲染完毕后获取轮播图与新闻数据
  useEffect(() => {
    (async () => {
      const res = await Api.queryNewsLatest();
      setToday(res.date);

      newList.push({
        date: res.date,
        stories: res.stories,
      });
      setNewList([...newList]); // 需要给不同地址的数组，让视图更新。如果地址一致则不会触发更新
      setBannerDate(res.top_stories);
    })();
  }, []);

  // 第一次渲染完毕，设置监听器，实现触底加载
  useEffect(() => {
    let ob = new IntersectionObserver(async (changes) => {
      let { isIntersecting } = changes[0];
      if (isIntersecting) {
        // 获取新的数据
        try {
          let times = newList.length > 0 && newList[newList.length - 1]["date"];
          const res = await Api.queryNewsLatest(times);
          let newArr = newList;
          newArr.push({
            date: res.date,
            stories: res.stories,
          });
          setNewList([...newArr]);
        } catch (error) {
          console.log(error);
        }
      }
    });

    ob.observe(loadmore.current);

    // 销毁时loadmore.current已经没了，而通过变量保存的值还在，因此需要用变量保存
    let loadmoreRef = loadmore.current;

    // 事件销毁，手动销毁监听器
    return () => {
      ob.unobserve(loadmoreRef);
      ob = null;
    };
  }, []);

  return (
    <div className="home-box">
      {/* 头部 */}
      <HomeHead today={today} />

      {/* 轮播图 */}
      <div className="swiper-box">
        {bannerData.length > 0 ? (
          <Swiper autoplay={true} loop={true}>
            {bannerData.map((item) => {
              return (
                <Swiper.Item key={item.id}>
                  <Link to={{ pathname: `/detail/${item.id}` }}>
                    <Image src={item.image} lazy />
                    <div className="desc">
                      <h3 className="title">{item.title}</h3>
                      <p className="author">{item.hint}</p>
                    </div>
                  </Link>
                </Swiper.Item>
              );
            })}
          </Swiper>
        ) : null}
      </div>

      {/* 新闻列表 */}
      {newList.length > 0 ? (
        newList.map((item, index) => {
          return (
            <div key={index} className="news-box">
              <Divider contentPosition="left">
                {formatTime(item.date, "{1}月{2}日")}
              </Divider>
              <div className="list">
                {item.stories.map((child) => {
                  return <NewsItem key={child.id} child={child} />;
                })}
              </div>
            </div>
          );
        })
      ) : (
        <MySkeleton />
      )}

      {/* 加载更多 */}
      <div
        className="loadmore-box"
        style={{ display: newList.length === 0 ? "none" : "flex" }}
        ref={loadmore}
      >
        <DotLoading />
        加载更多
      </div>
    </div>
  );
}
